package com.yituo.mjworld.mvc.action.user;

import com.yituo.mjworld.core.annotation.Ban;
import com.yituo.mjworld.core.annotation.Check;
import com.yituo.mjworld.core.annotation.Rule;
import com.yituo.mjworld.core.exception.MyException;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.mvc.action.IBaseAction;
import com.yituo.mjworld.mvc.entity.web.WebImgArr;
import com.yituo.mjworld.mvc.service.impl.ImageArrayServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

/**
 * 商品相关的图片处理模块
 */
@Component
public class ImageArrayAction implements IBaseAction {
  @Autowired
  ImageArrayServiceImpl imageArrayService;

  /**
   * 获取图片数组.
   * <p>
   * 获取成功返回某
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Rule(name = "id", name_zn = "图片数组ID", min = "0")
  public void getImageArray(MyHttpRequest req, MyHttpResponse res) throws IOException {
    int imgArrId = Integer.parseInt(req.getParameter("id"));
    WebImgArr imageArray= imageArrayService.getImageArray(imgArrId);
    if(imageArray==null){
      res.success(new ArrayList<>());
    }else{
      res.success(imageArray);
    }
  }

  /**
   * 用不到此接口
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Ban
  @Override
  public void getList(MyHttpRequest req, MyHttpResponse res) throws IOException {

  }

  @Ban
  @Override
  public void delete(MyHttpRequest req, MyHttpResponse res) throws IOException {

  }

  /**
   * 删除图片数组中的指定的一张图片
   *
   * @param req
   * @param res
   * @throws IOException
   */
  public void deleteTheImage(MyHttpRequest req, MyHttpResponse res) throws IOException {
    int imageArrId = -1;
    int index = -1;
    try {
      imageArrId = Integer.parseInt(req.getParameter("id"));
      index = Integer.parseInt(req.getParameter("index"));
      if (imageArrId <= 0 || index <= 0) {
        throw new MyException("");
      }
    } catch (Exception ex) {
      res.failedFor302("图片数组ID和index不合法!");
      return;
    }
    res.setResult(imageArrayService.deleteTheImage(imageArrId, index));
  }

  /**
   * @param req
   * @param res
   * @throws IOException
   */
  @Override
  @Check(form = WebImgArr.class)
  public void saveOrUpdate(MyHttpRequest req, MyHttpResponse res) throws IOException, InvocationTargetException, IllegalAccessException {
    res.setResult(imageArrayService.saveOrUpdate(req.getForm()));
  }
}
